﻿using System.IO;
using System.Text;

namespace UtilZ.Dotnet.Ex.Communication.Net.BMQ
{
    /// <summary>
    /// BMQ文本消息
    /// </summary>
    public class BMQTextMessage : BMQDataMessageAbs
    {

        private string _text;
        /// <summary>
        /// 文本内容
        /// </summary>
        public string Text
        {
            get { return _text; }
            set { _text = value; }
        }


        /// <summary>
        /// 构造函数-解析
        /// </summary>
        public BMQTextMessage()
            : base(BMQMessageTypes.TextMessage)
        {

        }


        /// <summary>
        /// 构造函数-创建
        /// </summary>
        /// <param name="topic">订阅主题</param>
        /// <param name="text">文本内容</param>
        public BMQTextMessage(short topic, string text)
            : base(BMQMessageTypes.TextMessage, topic)
        {
            this._text = text;
        }



        /// <summary>
        /// 获取消息大小
        /// </summary>
        /// <returns>消息大小</returns>
        protected override int GetMessageSize()
        {
            if (string.IsNullOrEmpty(this._text))
            {
                return BMQ_DATA_HEADER_SIZE;
            }

            return BMQ_DATA_HEADER_SIZE + Encoding.UTF8.GetByteCount(this._text);
        }


        /// <summary>
        /// 写消息内容到BinaryWriter
        /// </summary>
        /// <param name="writer">消息写器</param>
        protected override void WriteContent(BinaryWriter writer)
        {
            if (this._text == null)
            {
                return;
            }

            writer.Write(Encoding.UTF8.GetBytes(this._text));
        }

        /// <summary>
        /// 读取消息内容
        /// </summary>
        /// <param name="reader">内容二进制数据</param>
        /// <param name="dataLength">数据字节数</param>
        protected override void ReadContent(BinaryReader reader, int dataLength)
        {
            byte[] data = reader.ReadBytes(dataLength);
            this._text = Encoding.UTF8.GetString(data);
        }

    }
}
